import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:richedit/constant.dart';
import 'package:richedit/convert/convert.dart';
import 'package:richedit/data/audio_entity.dart';
import 'package:richedit/data/divider_entity.dart';
import 'package:richedit/data/doc_entity.dart';
import 'package:richedit/data/image_entity.dart';
import 'package:richedit/data/image_group_entity.dart';
import 'package:richedit/data/text_entity.dart';
import 'package:richedit/data/video_entity.dart';
import 'package:richedit/widget/audio_widget.dart';
import 'package:richedit/widget/divider_widget.dart';
import 'package:richedit/widget/doc_widget.dart';
import 'package:richedit/widget/image_group_widget.dart';
import 'package:richedit/widget/image_widget.dart';
import 'package:richedit/widget/text_widget.dart';
import 'package:richedit/widget/video_widget.dart';

class EditPage extends StatefulWidget {
  final String? editData;

  const EditPage({Key? key, this.editData}): super(key: key);

  @override
  EditPageState createState() => EditPageState();
}

class EditPageState extends State<EditPage> {
  late List _dataList;
  int _selectIndex = -1;

  @override
  void initState() {
    _dataList = Convert.string2EntityList(widget.editData);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: ListView(
          physics: BouncingScrollPhysics(),
          children: [
            ListView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: _dataList.length,
                itemBuilder: (context, index) {
                  return _addItem(_dataList[index], index);
                }),
            Container(
              height: 200,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => _add(),
      ),
    );
  }

  Widget _addItem(dynamic data, int index) {
    Widget widget;
    switch (data.name) {
      case WidgetType.Text:
        widget = TextEdit(data);
        break;
      case WidgetType.Divider:
        widget = DividerEdit(data);
        break;
      case WidgetType.Image:
        widget = ImageEdit(data);
        break;
      case WidgetType.Video:
        widget = VideoEdit(data);
        break;
      case WidgetType.Audio:
        widget = AudioEdit(data);
        break;
      case WidgetType.Doc:
        widget = DocEdit(data);
        break;
      case WidgetType.ImageGroup:
        widget = ImageGroupEdit(data);
        break;
      default:
        widget = Text("TODO");
        break;
    }
    return Stack(
      // key: GlobalKey(),
      children: [
        Positioned.fill(
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              // NavigatorUtils.unfocus();
              setState(() {
                _selectIndex = index;
              });
            },
            child: Container(
              color: index == _selectIndex ? Colors.grey[200] : Colors.white,
            ),
          ),
        ),
        Row(
          children: [
            GestureDetector(
                onTap: () {
                  // NavigatorUtils.unfocus();
                  setState(() {
                    _selectIndex = index;
                  });
                },
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Icon(Icons.apps),
                )),
            Expanded(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: index == _selectIndex ? 16 : 4),
                child: widget,
              ),
            ),
          ],
        ),
        _selectIndex == index
            ? Positioned(
                top: 0,
                right: 0,
                child: Row(
                  children: [
                    FloatingActionButton(
                        mini: true,
                        heroTag: "edit$index",
                        backgroundColor: Colors.blue[300],
                        child: Icon(
                          Icons.edit,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          // NavigatorUtils.unfocus();
                          showSetting(data);
                        }),
                    FloatingActionButton(
                        mini: true,
                        heroTag: "delete$index",
                        backgroundColor: Colors.red[300],
                        child: Icon(
                          Icons.delete,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          // NavigatorUtils.unfocus();
                          setState(() {
                            _dataList.removeAt(index);
                          });
                        })
                  ],
                ))
            : Container(),
      ],
    );
  }

  void showSetting(dynamic data) {
    switch (data.name) {
      case WidgetType.Text:
        showTextSetting(context, data, (data) {
          setState(() {});
        });
        return;
      case WidgetType.Divider:
        showDividerSetting(context, data, (data) {
          setState(() {});
        });
        return;
      case WidgetType.ImageGroup:
        showImageGroupSetting(context, data, (data) {
          setState(() {});
        });
        return;
      case WidgetType.Audio:
        showAudioSetting(context, data, (data){
          setState(() {

          });
        });
        return;
    }
  }

  String getEditData() {
    return Convert.entityList2String(_dataList);
  }

  void _add() {
    // NavigatorUtils.unfocus();
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (context) {
          return Container(
            width: double.infinity,
            height: 200,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)),
              color: Colors.white,
            ),
            child: GridView.count(
              physics: BouncingScrollPhysics(),
              crossAxisCount: 4,
              children: [
                IconButton(
                  icon: Icon(Icons.text_fields),
                  onPressed: () {
                    Navigator.of(context).pop(WidgetType.Text);
                  },
                ),
                IconButton(
                  icon: Icon(Icons.linear_scale),
                  onPressed: () {
                    Navigator.of(context).pop(WidgetType.Divider);
                  },
                ),
                IconButton(
                  icon: Icon(Icons.image),
                  onPressed: () {
                    Navigator.of(context).pop(WidgetType.Image);
                  },
                ),
                IconButton(
                  icon: Icon(Icons.ondemand_video_rounded),
                  onPressed: () {
                    Navigator.of(context).pop(WidgetType.Video);
                  },
                ),
                IconButton(
                  icon: Icon(Icons.radio),
                  onPressed: () {
                    Navigator.of(context).pop(WidgetType.Audio);
                  },
                ),
                IconButton(
                  icon: Icon(Icons.file_copy),
                  onPressed: () {
                    Navigator.of(context).pop(WidgetType.Doc);
                  },
                ),
                IconButton(
                    icon: Icon(Icons.photo_library),
                    onPressed: () {
                      Navigator.of(context).pop(WidgetType.ImageGroup);
                    })
              ],
            ),
          );
        }).then((value) {
      if (value is String) {
        int insertIndex;
        if (_selectIndex > -1 && _selectIndex < _dataList.length) {
          insertIndex = _selectIndex + 1;
        } else {
          insertIndex = _dataList.length;
        }
        switch (value) {
          case WidgetType.Text:
            _dataList.insert(
                insertIndex,
                TextEntity()
                  ..name = WidgetType.Text
                  ..bold = false
                  ..align = "0"
                  ..color = "#333333"
                  ..fontSize = "14"
                  ..italic = false);
            break;
          case WidgetType.Divider:
            _dataList.insert(
                insertIndex,
                DividerEntity()
                  ..name = WidgetType.Divider
                  ..color = Convert.color2String(Colors.black54)
                  ..height = 1);
            break;
          case WidgetType.Image:
            _dataList.insert(insertIndex, ImageEntity()..name = WidgetType.Image);
            break;
          case WidgetType.Video:
            _dataList.insert(insertIndex, VideoEntity()..name = WidgetType.Video);
            break;
          case WidgetType.Audio:
            _dataList.insert(insertIndex, AudioEntity()..name = WidgetType.Audio);
            break;
          case WidgetType.Doc:
            _dataList.insert(insertIndex, DocEntity()..name = WidgetType.Doc);
            break;
          case WidgetType.ImageGroup:
            _dataList.insert(
                insertIndex,
                ImageGroupEntity()
                  ..name = WidgetType.ImageGroup
                  ..isHorizontal = true
                  ..children = [
                    ImageEntity()..name = WidgetType.Image,
                    ImageEntity()..name = WidgetType.Image,
                  ]);
            break;
        }
        _selectIndex = insertIndex;
        setState(() {});
      }
    });
  }
}

